﻿using AyaWo.Commen;
using AyaWo.DbF;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AyaWo.WinFrom
{
    public partial class ConnForm : Form
    {
        public ConnForm()
        {
            InitializeComponent();
            try
            {
                var va = DatHelper<ConnStr>.GetDat("connStr.dat");
                if (va != null)
                {
                    textBox1.Text = va.connstr;
                    comboBox1.Text = va.DbType;
                }
            }
            catch
            {
                textBox1.Text = "";
            }
        }

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            string connStr = textBox1.Text.Trim();
            string typ = comboBox1.Text;

            SqlSourceType sty = SqlSourceType.SqLite;
            if (typ == "SqLite")
            { }
            else
                sty = SqlSourceType.MySql;

            DbHelper dh = new DbHelper(connStr, sty);
            try
            {
                dh.OpenConnection();
                MessageBox.Show("连接字符串正确....");
            }
            catch
            {
                MessageBox.Show("连接字符串错误....");
            }
            finally
            {
                dh.Dispose();
            }
        }

        /// <summary>
        /// 保存连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                string typ = comboBox1.Text;
                SqlSourceType sty = SqlSourceType.SqLite;
                if (typ == "SqLite")
                { }
                else
                    sty = SqlSourceType.MySql;
                string connStr = textBox1.Text.Trim();

                ConnStr conn = new ConnStr { connstr=connStr , DbType=sty.ToString()};
               
                DatHelper<ConnStr>.SaveDat("connStr.dat", JsonConvert.SerializeObject(conn));

                DbHelper dh = new DbHelper(connStr, sty);
                try
                {
                    dh.OpenConnection();
                }
                catch
                {
                    MessageBox.Show("连接字符串错误....");
                    return;
                }

                MessageBox.Show("保存成功....");
                DialogResult = DialogResult.OK;
                this.Close();
            }
            catch
            {
                MessageBox.Show("保存失败....");
            }

        }
    }
}
